package com.oa.tools.utils;

import java.net.ConnectException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.oa.tools.utils.http.OKHttpClientUtil;

public class MailUtil {
	
	//https://exmail.qq.com/qy_mng_logic/doc#10008
	public static final Logger logger = LoggerFactory.getLogger(MailUtil.class);
	
	public static void sendMail(String[] receiveMailAccounts, String subject,String content) throws Exception {
		String sendMailAccount = SysConfig.getSysString("发送邮箱");
		String password = SysConfig.getSysString("发送邮箱密码");
		sendMail(sendMailAccount, password, receiveMailAccounts, subject, content,false);
	}
	
	public static void sendMail(String sendMailAccount, String password, String[] receiveMailAccounts, String subject,
			String content,boolean withImg) throws Exception {
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.smtp.host", "smtp.exmail.qq.com");//smtp.exmail.qq.com:465
		props.setProperty("mail.smtp.auth", "false");
	    props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.smtp.socketFactory.fallback", "true");
        props.setProperty("mail.smtp.socketFactory.port", "465");

		Session session = Session.getInstance(props);
		session.setDebug(true);

		MimeMessage message = null;
		if(withImg) {
			message = createImageMessage(session, sendMailAccount, receiveMailAccounts, subject, content);
		}else {
			message = createMimeMessage(session, sendMailAccount, receiveMailAccounts, subject, content);
		}

		Transport transport = session.getTransport();

		transport.connect(sendMailAccount, password);

		transport.sendMessage(message, message.getAllRecipients());

		transport.close();
	}

	public static MimeMessage createMimeMessage(Session session, String sendMail, String[] receiveMails, String subject,
			String content) throws Exception {
		MimeMessage message = new MimeMessage(session);

		message.setFrom(new InternetAddress(sendMail, sendMail, "UTF-8"));

		InternetAddress [] addrs = new InternetAddress[receiveMails.length];
		for (int i=0;i<receiveMails.length;i++) {
			String receiveMail = receiveMails[i];
			addrs[i] =  new InternetAddress(receiveMail, receiveMail, "UTF-8");
		}
		message.setRecipients(MimeMessage.RecipientType.TO, addrs);
		
		message.setSubject(subject, "UTF-8");

		message.setContent(content, "text/html;charset=UTF-8");

		message.setSentDate(new Date());
		
		message.saveChanges();

		return message;
	}
	
	public static MimeMessage createImageMessage(Session session, String sendMail, String[] receiveMails, String subject,
			String content) throws Exception {
		MimeMessage message = new MimeMessage(session);

		message.setFrom(new InternetAddress(sendMail, sendMail, "UTF-8"));

		InternetAddress [] addrs = new InternetAddress[receiveMails.length];
		for (int i=0;i<receiveMails.length;i++) {
			String receiveMail = receiveMails[i];
			addrs[i] =  new InternetAddress(receiveMail, receiveMail, "UTF-8");
		}
		message.setRecipients(MimeMessage.RecipientType.TO, addrs);
		
		message.setSubject(subject, "UTF-8");

		message.setSentDate(new Date());
		
		MimeMultipart multipart = new MimeMultipart("related");

        // first part  (the html)
        BodyPart messageBodyPart = new MimeBodyPart();
        String htmlText = "<pre>"+content+"</pre><img src=\"cid:image1\"><br/><img src=\"cid:image2\">";
        messageBodyPart.setContent(htmlText, "text/html");

        // add it
        multipart.addBodyPart(messageBodyPart);

        // second part (the image)
        messageBodyPart = new MimeBodyPart();
        DataSource fds = new FileDataSource("C:\\images\\self-setting-access.png");
        messageBodyPart.setDataHandler(new DataHandler(fds));
        messageBodyPart.setHeader("Content-ID","<image1>");
        // add it
        multipart.addBodyPart(messageBodyPart);
        
        // second part (the image)
        messageBodyPart = new MimeBodyPart();
        DataSource fds1 = new FileDataSource("C:\\images\\chg-pass.png");
        messageBodyPart.setDataHandler(new DataHandler(fds1));
        messageBodyPart.setHeader("Content-ID","<image2>");
        // add it
        multipart.addBodyPart(messageBodyPart);

        // put everything together
        message.setContent(multipart);
		
		message.saveChanges();

		return message;
	}
	
	
	public static String getEmailUserInfo(String email) throws Exception {
		String url = "https://api.exmail.qq.com/cgi-bin/gettoken?corpid=wmd96f35beef7a0a0f&corpsecret=oycrJ9_5zYag_urUZZzmq_t5tas-foPgj2xtfcg1SN4fqEoyyDk6fPYncu5NAg_E";
		String[] bodyString = OKHttpClientUtil.httpGet(url, null, null);
		String access_token = ObjectUtil.json2Map(bodyString[0]).get("access_token").toString();

		url = "https://api.exmail.qq.com/cgi-bin/user/get?access_token=" + access_token + "&userid=" + email;

		bodyString = OKHttpClientUtil.httpGet(url, null, null);
		return bodyString[0];
	}
	
	public static String getAllEmailUserInfo() throws Exception {
		String url = "https://api.exmail.qq.com/cgi-bin/gettoken?corpid=wmd96f35beef7a0a0f&corpsecret=oycrJ9_5zYag_urUZZzmq_t5tas-foPgj2xtfcg1SN4fqEoyyDk6fPYncu5NAg_E";
		String[] bodyString = OKHttpClientUtil.httpGet(url, null, null);
		String access_token = ObjectUtil.json2Map(bodyString[0]).get("access_token").toString();

		url = "https://api.exmail.qq.com/cgi-bin/user/simplelist?access_token=" + access_token + "&department_id=1&fetch_child=1";

		for(int i=0;i<3;i++) {
			try {
				bodyString = OKHttpClientUtil.httpGet(url, null, null);
			} catch (ConnectException e) {
				e.printStackTrace();
				continue;
			}catch (Exception e) {
				e.printStackTrace();
			}
			break;
		}
		
		
		return bodyString[0];
	}
	
	/**
	 * 创建邮箱
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public static String createEmail(CreateEmailRequest request) throws Exception {
		String resultMsg = getEmailUserInfo(request.userid);
		Object mobileStr = ObjectUtil.json2Map(resultMsg).get("mobile");
		if (mobileStr != null) {
			if (mobileStr.equals(request.mobile)) {
				return "userid created";
			}
			return "userid existed";
		}

		String url = "https://api.exmail.qq.com/cgi-bin/gettoken?corpid=wmd96f35beef7a0a0f&corpsecret=oycrJ9_5zYag_urUZZzmq_t5tas-foPgj2xtfcg1SN4fqEoyyDk6fPYncu5NAg_E";
		String[] bodyString = OKHttpClientUtil.httpGet(url, null, null);

		String access_token = ObjectUtil.json2Map(bodyString[0]).get("access_token").toString();

		url = "https://api.exmail.qq.com/cgi-bin/user/create?access_token=" + access_token;

		Map<String, Object> params = new HashMap<>();
		params.put("userid", request.userid);
		params.put("name", request.name);
		params.put("department", request.depids);
		params.put("position", request.position);
		params.put("mobile", request.mobile);
		params.put("tel", request.tel);
		params.put("extid", request.extid);
		params.put("gender", request.gender);
		params.put("password", request.password);

		bodyString = OKHttpClientUtil.httpJsonPost(url, params, null);

		if ("0".equals(ObjectUtil.json2Map(bodyString[0]).get("errcode") + ""))
			resultMsg = "ok";
		else {
			resultMsg = bodyString[0];
		}
		return resultMsg;
	}
	
	public static String updateEmail(UpdateEmailRequest request) throws Exception {

		Map<String, Object> params = new HashMap<>();
		params.put("userid", request.userid);
		params.put("name", request.name);
		params.put("department", request.depids);
		params.put("position", request.position);
		params.put("mobile", request.mobile);
		params.put("tel", request.tel);
		params.put("extid", request.extid);
		params.put("gender", request.gender);
		String bodyString = OKHttpClientUtil.updateEmail(params);

		return bodyString;
	}
	
	public static String disableEmail(String userid) throws Exception {

		Map<String, Object> params = new HashMap<>();
		params.put("userid", userid);
		params.put("enable", 0);
		String bodyString = OKHttpClientUtil.updateEmail(params);

		return bodyString;
	}
	
	
	
	
	/**
	 * 创建邮箱保证完成（重复则增加序号）
	 * @param name
	 * @param dep
	 * @param position
	 * @param mobile
	 * @param tel
	 * @param code
	 * @param gender
	 * @return
	 * @throws Exception
	 */
	public static String createEmail2Ok(String name, String dep, String position, String mobile, String tel,
			String code, String gender) throws Exception {
		String name1 = name;
		Map<String,String> familynameMap = SysConfig.getSysMap("多音字姓");
		
		for (String key : familynameMap.keySet()) {
			String val = (String) familynameMap.get(key);
			if (name.startsWith(key)) {
				name1 = name1.replaceFirst(key, val);
				break;
			}
		}

		Map<String,String> lastnameMap = SysConfig.getSysMap("多音字名");
		
		for (String key : lastnameMap.keySet()) {
			String val = (String) lastnameMap.get(key);
			if (name.contains(key)) {
				name1 = name1.replace(key, val);
				break;
			}
		}

		String logname = StringUtil.getPinyin(name1);
		CreateEmailRequest req = new CreateEmailRequest(logname, name, dep, position, mobile, tel, code, gender);
		UpdateEmailRequest updateEmailRequest = req.toUpdateEmailRequest();
		
		
		Pattern p = Pattern.compile("([a-z]+)(\\d+)");
		String resultmsg = MailUtil.createEmail(req);
		if ("userid created".equals(resultmsg)) {
			resultmsg = MailUtil.updateEmail(updateEmailRequest);
			logger.info(name + "(" + mobile + "):" + logname + "@fengbangleasing.com邮箱已创建，更新返回：" + resultmsg);
		}else if ("ok".equals(resultmsg)) {
			logger.info(name + "(" + mobile + "):" + logname + "@fengbangleasing.com邮箱创建完成！" + resultmsg);
		}else if ("userid existed".equals(resultmsg)) {
			for (int tmpi = 1; tmpi < 10; tmpi++) {
				Matcher m = p.matcher(logname);
				String name_tmp =null;
				String logname_num_tmp=null;
				boolean findFlag = false;
				while(m.find()) {
					name_tmp=m.group(1);
					logname_num_tmp=m.group(2);
					findFlag = true;
				}
				if(findFlag) {
					int num = (Integer.parseInt(logname_num_tmp)+1);
					if(num<10) {
						logname = name_tmp+"0"+num;
					}else {
						logname = name_tmp+num;
					}
				}else {
					logname = logname + "01";
				}
				

				req.userid = (logname + "@fengbangleasing.com");
				resultmsg = createEmail(req);
				if ("userid created".equals(resultmsg)) {
					logger.info(name + "(" + mobile + "):" + logname + "@fengbangleasing.com邮箱创建完成！" + resultmsg);
					break;
				}
				if (!"userid existed".equals(resultmsg)) {
					if ("ok".equals(resultmsg)) {
						logger.info(name + "(" + mobile + "):" + logname + "@fengbangleasing.com邮箱创建完成！" + resultmsg);
						break;
					}else {
						logger.error(name + "(" + mobile + "):" + logname + "@fengbangleasing.com邮箱创建报错！" + resultmsg);
					}
				}
			}
		}else if (resultmsg.contains("invalid mobile")) {//{"errcode":60103,"errmsg":"invalid mobile"}
			logger.error(name + "(" + mobile + "):" + logname + "@fengbangleasing.com邮箱创建报错！手机号问题：" + resultmsg);
			throw new RuntimeException(name + "(" + mobile + "):" + logname + "@fengbangleasing.com邮箱创建报错！手机号问题：" + resultmsg);
		} else {
			logger.error(name + "(" + mobile + "):" + logname + "@fengbangleasing.com邮箱创建报错！" + resultmsg);
			throw new RuntimeException(name + "(" + mobile + "):" + logname + "@fengbangleasing.com邮箱创建报错！" + resultmsg);
		}

		return logname;
	}
	
	public static class CreateEmailRequest {
		private String userid;
		private String name;
		private List<Long> depids;
		private String position;
		private String mobile;
		private String tel;
		private String extid;
		private String gender;
		private String password;

		public CreateEmailRequest(String logname, String name, String deptname, String position, String mobile,
				String tel, String fbcode, String gender) {
			List<Long> depids = new ArrayList<Long>();
			
			if(!StringUtil.isBlank(deptname)) {
				String depname = deptname;//.replaceAll("\\-[^\\-]+?门店", "");
				
				Map<String,String> deptNameIdMapping= SysConfig.getMap("新入职流程处理配置", "腾讯邮箱部门ID");
				String deptId = deptNameIdMapping.get(depname);
				
				if(deptId==null) {
					throw new RuntimeException("未知的邮箱部门："+depname);
				}
				
				depids.add(Long.valueOf(deptId));
			}else {
				throw new RuntimeException("未设置邮箱部门");
			}
			
			

			this.userid = (logname + "@fengbangleasing.com");
			this.name = name;
			this.depids = depids;
			this.position = position;
			this.mobile = mobile;
			this.tel = tel;
			this.extid = fbcode;
			this.gender = (gender.equals("男") ? "1" : "2");
			this.password = ("Fb" + mobile);
		}
		
		public UpdateEmailRequest toUpdateEmailRequest() {
			UpdateEmailRequest updateEmailRequest = new UpdateEmailRequest();
			
			updateEmailRequest.userid = this.userid;
			updateEmailRequest.name = this.name;
			updateEmailRequest.depids=this.depids;
			updateEmailRequest.position=this.position;
			updateEmailRequest.mobile = this.mobile;
			updateEmailRequest.tel=this.tel;
			updateEmailRequest.extid=this.extid;
			updateEmailRequest.gender=this.gender;
			updateEmailRequest.password=this.password;
			return updateEmailRequest;
		}
	}
	
	
	public static class UpdateEmailRequest {
		private String userid;
		private String name;
		private List<Long> depids;
		private String position;
		private String mobile;
		private String tel;
		private String extid;
		private String gender;
		private String password;

		public UpdateEmailRequest() {}
		public UpdateEmailRequest(String logname, String name, String deptname, String position, String mobile,
				String tel, String fbcode, String gender) {
			List<Long> depids = new ArrayList<Long>();
			
			if(!StringUtil.isBlank(deptname)) {
				String depname = deptname;//.replaceAll("\\-[^\\-]+?门店", "");
				
				Map<String,String> deptNameIdMapping= SysConfig.getMap("新入职流程处理配置", "腾讯邮箱部门ID");
				String deptId = deptNameIdMapping.get(depname);
				if(deptId!=null) {
					depids.add(Long.valueOf(deptId));
				}
			}

			this.userid = (logname + "@fengbangleasing.com");
			this.name = name;
			this.depids = depids;
			this.position = position;
			this.mobile = mobile;
			this.tel = tel;
			this.extid = fbcode;
			this.gender = (gender.equals("男") ? "1" : "2");
//			this.password = ("Fb" + mobile);
		}
	}

	public static void main(String[] args) throws Exception {
		StringBuilder content = new StringBuilder();
//		content.append("<h1>欢迎加入沣邦大家庭!</h1><br/><pre>");
//		content.append("OA访问地址：");content.append("http://oa.fengbangleasing.com");content.append("\r\n");
//		content.append("OA登录名：");content.append("sushaolei");content.append("\r\n");
//		content.append("初始密码：");content.append("Fb13333333");content.append("\r\n");
//		content.append("姓名：");content.append("苏少雷");content.append("\r\n");
//		content.append("工号：");content.append("1234");content.append("\r\n");
//		content.append("手机：");content.append("133333333");content.append("\r\n");
//		content.append("部门：");content.append("信息技术部");content.append("\r\n");
//		content.append("邮箱：");content.append("sushaolei@fengbangleasing.com");content.append("\r\n");
//		content.append("固话：");content.append("66290010");content.append("\r\n");
//		content.append("</pre>");
//		
//		content.append("手机端KK下载如下：<br/>");
//		content.append("<img src='http://oa-tool.fengbangleasing.com/images/kk-access.png'/><br/>");
//		content.append("<img src='http://oa-tool.fengbangleasing.com/images/kk-base-settings.png'/>");
//		
//    	MailUtil.sendMail(new String[] {"sushaolei@fengbangleasing.com"}, "工作邮箱和OA账号创建通知", content.toString());
		
		System.out.println(disableEmail("sushaolei@fengbangleasing.com"));
	}
	
	public static String getEmailDeptList() throws Exception {
		String url = "https://api.exmail.qq.com/cgi-bin/gettoken?corpid=wmd96f35beef7a0a0f&corpsecret=oycrJ9_5zYag_urUZZzmq_t5tas-foPgj2xtfcg1SN4fqEoyyDk6fPYncu5NAg_E";
		String[] bodyString = OKHttpClientUtil.httpGet(url, null, null);

		String access_token = ObjectUtil.json2Map(bodyString[0]).get("access_token").toString();

		url = " https://api.exmail.qq.com/cgi-bin/department/list?access_token=" + access_token+"&id=0";
		
		bodyString =OKHttpClientUtil.httpGet(url, null, null);
		return bodyString[0];
	}
}